/**
 * 公共接口
 *
**/

//ajax
import fetch from 'isomorphic-fetch'

export function myAjax(url, method, param, callback1, callback2) {
	fetch(url, { 
		    method: method,
		    headers: { 
		      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" 
		    }, 
			 body: analysisJson(param) 
			})
			.then((response) => {
				if (response.ok) {
				    response.json().then((data) => callback1(data));
				  } else {
				  	callback2(response)
				    console.log("Looks like the response wasn't perfect, got status", response.status);
				  }

			})
			.catch(function (error) {
				callback2(error)
			    console.log('Request failed', error);
			});

}

export function myAjaxJson(url, method, param, callback1, callback2) {
	fetch(url, {
		    method: method,
		    headers: {
		      "Content-type": "application/json; charset=UTF-8"
		    },
			  body: JSON.stringify(param)
			})
			.then((res) => {
				if (res.ok) {
				    res.json().then((data) => callback1(data));
				  } else {
				  	callback2(res)
				    console.log("Looks like the response wasn't perfect, got status", res.status);
				  }

			})
			.catch(function (error) {
			  	callback2(error)
			    console.log('Request failed', error);
			});

}

function analysisJson(obj) {
    let str = ""
    for (let key in obj) {
        str += key + "=" + obj[key] + '&'
    }
    return str.substr(0,str.length - 1);
}

export function http(data,url,callback1,callback2) {
	var xmlhttp;
	function createXHttpRequest() {
		if (window.ActiveXObject) {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else if (window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();
		}
		else {
			return;
		}
	}

	function starRequest(data) {
		createXHttpRequest();
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200) {
					callback1();
				}else{
					callback2();
				}
			}
		};
		xmlhttp.open("POST", url, true);
		xmlhttp.send(data);
	}
	starRequest(data);
}
export const objToForm = function (data) {
    let d = "";
    Object.keys(data).forEach(function(key) {
        d += `${key}=${data[key]}&`
    })
    return d;
}

export const fetchFromCommonGet = function(url, data, callback1, callback2) {
    fetch(ROOTURL + url + `?${objToForm(data)}`,{
        credentials: 'include'
    }).then(function(response) {
        return response.json()
    }).then(function(json) {
        if (callback1 && callback1 != '') {
            callback1(json);
        }
    }).catch(function(ex) {
        if (callback2 && callback2 != '') {
            callback2(ex);
        }
    })
}

//以表单格式请求数据  ---普通版
export const fetchFromCommon = function(url, method, data, callback1, callback2) {
    fetch(ROOTURL + url, {
        method: method,
        headers: {"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"},
        credentials: 'include',
        body: objToForm(data)
    }).then(function(response) {
        return response.json()
    }).then(function(json) {
        if (callback1 && callback1 != '') {
            callback1(json);
        }
    }).catch(function(ex) {
        if (callback2 && callback2 != '') {
            callback2(ex);
        }
    })
}
export const fetchFromCommonText = function(url, method, data, callback1, callback2) {
    fetch(ROOTURL + url, {
        method: method,
        headers: {"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"},
        credentials: 'include',
        body: objToForm(data)
    }).then(function(response) {
        return response.text()
    }).then(function(json) {
        if (callback1 && callback1 != '') {
            callback1(json);
        }
    }).catch(function(ex) {
        if (callback2 && callback2 != '') {
            callback2(ex);
        }
    })
}

// 获取客户信息 
export const customerInfo = function(callback) {

    let _url = ROOTURL + 'customer/profile/me.api'
	fetch(_url, {
          	method : 'GET',
          	credentials: 'include',
          	Cookie: document.cookie,
          	header: 'application/json; charset=utf-8',
          	}).then(res=>{
              	if(res.ok){
                  	res.json().then(data=>{
	    		        localStorage.setItem("userInfo", JSON.stringify(data));
	    		        let url = ROOTURL + 'customer/profile/pull-wxmp.api';
					    fetch(url, {
					          	method : 'POST',
					          	credentials: 'include',
					          	Cookie: document.cookie,
					          	headers: {"Content-Type": "application/x-www-form-urlencoded"},
					          	body: "openid="+data.openidRep,
					          	}).then(res=>{
					              	if(res.ok){
					                  	res.json().then(data=>{
					    		        	localStorage.setItem("customerInfo", JSON.stringify(data));
					    		        	callback()
					                  	})
					              	}
					          	})
						})
				}
    		})

}
export function getParamValue(name){
    try {
    	return(
        	location.search.match(new RegExp("[\?&]"+name+"=[^&#]*"))[0].split("=")[1]
    	);
    } catch (ex) {
    	return(null);
    }
}


export const ROOTURL = 'http://meng.fashcollege.com/pepper/'
export const ROOTAPI = 'http://meng.fashcollege.com/diykabuy/'
// export const ROOTPATH = 'http://fxyweixin.uutime.cn/personal/'

/**
* 公用函数
*/
//动态生成路径

export function DynPath(route) {

	return ROOTPATH+route;
}
